package com.yeulaptrinh.jsonparsing;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class ListViewActivity extends ListActivity {

	static final String URL = "http://yeulaptrinh.vn/demo/jsonparsing.php";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
		
		JSONArray data = null;
		
		ArrayList<String> menuItems = new ArrayList<String>();
		JSONParser jsonParser = new JSONParser();
		JSONObject jObj = jsonParser.getJsonFromUrl(URL);
		
		try {
			data = jObj.getJSONArray("data");
			for(int i = 0; i < data.length(); i++) {
				menuItems.add(data.getString(i));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		setListAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, android.R.id.text1,
				menuItems));

		getListView().setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String product = ((TextView) view).getText().toString();
				Intent i = new Intent(getApplicationContext(),
						DetailViewActivity.class);
				i.putExtra("product", product);
				startActivity(i);
			}
		});
	}

}
